package cn.yajienet.data.elasticsearch.utils;

import cn.yajienet.data.elasticsearch.annotation.Document;
import cn.yajienet.data.elasticsearch.dto.DocumentEntity;
import cn.yajienet.data.elasticsearch.properties.ElasticSearchProperties;
import org.springframework.util.StringUtils;

import java.util.Map;

import static cn.yajienet.data.elasticsearch.ElasticSearchConstant.EL_END;
import static cn.yajienet.data.elasticsearch.ElasticSearchConstant.EL_START;

/**
 * @Author Wang Chenguang
 * @Email wcg.chen@foxmail.com
 * @Date on 2021/12/19
 * @Version 1.0.0
 * @Description 通用工具
 */
public class GeneralTools {

    private GeneralTools() {
    }

    public static DocumentEntity toDocumentEntity(Document document, String className, ElasticSearchProperties elasticSearchProperties, boolean cache) {
        Map<String, DocumentEntity> documents = elasticSearchProperties.getDocuments();
        String index = document.index();
        String alias = document.alias();
        if (StringUtils.hasLength( index )) {
            if (index.startsWith( EL_START ) && index.endsWith( EL_END )) {
                String newIndex = index.substring( 2, index.length() - 1 );
                if (StringUtils.hasLength( newIndex ) && documents.containsKey( newIndex )) {
                    DocumentEntity entity = documents.get( newIndex );
                    if (StringUtils.hasLength( entity.getVersion() )) {
                        entity.setIndex( entity.getIndex() + "-" + entity.getVersion() );
                    }
                    entity.setCache( cache );
                    return entity;
                }
            } else {
                return new DocumentEntity( index, alias, null, cache );
            }
        } else {
            String classNameLine = StringEsUtils.documentClassNameToLine( className );
            if (documents.containsKey( classNameLine )) {
                DocumentEntity entity = documents.get( classNameLine );
                if (StringUtils.hasLength( entity.getVersion() )) {
                    entity.setIndex( entity.getIndex() + "-" + entity.getVersion() );
                }
                if (StringUtils.hasLength( alias )) {
                    entity.setAlias( alias );
                }
                entity.setCache( cache );
                return entity;
            }
        }
        return null;
    }

}
